package cn.zhentao.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 语音通话控制器
 * 专门处理语音通话相关的API接口
 */
@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class VoiceCallController {

    @Value("${voice.call.app.id:13d9536a-37db-4d81-b35c-759105f1b8b7}")
    private String liveMicAppId;
    
    @Value("${voice.call.app.key:206cb794480515fa054ea20f02305dd4}")
    private String liveMicAppKey;

    /**
     * 获取RTC认证Token - 语音通话专用
     */
    @PostMapping("/api/v2/aiagent/getRtcAuthToken")
    public Map<String, Object> getRtcAuthToken(@RequestBody Map<String, Object> request) {
        try {
            String userId = (String) request.get("user_id");
            String channelId = (String) request.get("channel_id");

            log.info("获取RTC认证Token请求 - 用户ID: {}, 频道ID: {}", userId, channelId);

            // 验证必需参数
            if (userId == null || userId.trim().isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", 400);
                errorResult.put("message", "用户ID不能为空");
                return errorResult;
            }

            if (channelId == null || channelId.trim().isEmpty()) {
                channelId = UUID.randomUUID().toString().replaceAll("-", "");
            }

            long timestamp = getClientTimestamp();
            String rtcAuthToken = createBase64Token(channelId, userId, timestamp);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("rtc_auth_token", rtcAuthToken);
            result.put("timestamp", timestamp);
            result.put("channel_id", channelId);
            result.put("user_id", userId);

            log.info("RTC认证Token生成成功 - 用户ID: {}, Token: {}", userId, rtcAuthToken);
            return result;

        } catch (Exception e) {
            log.error("获取RTC认证Token异常: {}", e.getMessage(), e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "获取RTC认证Token失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 生成伴伴AI - 语音通话专用
     */
    @PostMapping("/api/v2/aiagent/generateAIAgentCall")
    public Map<String, Object> generateAIAgentCall(@RequestBody Map<String, Object> request) {
        try {
            String userId = (String) request.get("user_id");
            String aiAgentId = (String) request.get("ai_agent_id");
            String region = (String) request.get("region");

            log.info("生成伴伴AI请求 - 用户ID: {}, 伴伴AI ID: {}, 区域: {}", userId, aiAgentId, region);
            
            // 验证必需参数
            if (userId == null || userId.trim().isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", 400);
                errorResult.put("message", "用户ID不能为空");
                return errorResult;
            }

            // 生成实例信息
            String instanceId = UUID.randomUUID().toString();
            String channelId = "channel_" + System.currentTimeMillis();
            String rtcAuthToken = createBase64Token(channelId, userId, getClientTimestamp());

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            result.put("request_id", UUID.randomUUID().toString());
            result.put("ai_agent_instance_id", instanceId);
            result.put("channel_id", channelId);
            result.put("ai_agent_user_id", "ai_agent_" + System.currentTimeMillis());
            result.put("rtc_auth_token", rtcAuthToken);
            result.put("workflow_type", "VoiceChat");

            log.info("伴伴AI生成成功 - 实例ID: {}, 频道ID: {}", instanceId, channelId);
            return result;

        } catch (Exception e) {
            log.error("生成伴伴AI异常: {}", e.getMessage(), e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "生成伴伴AI失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 描述伴伴AI实例 - 语音通话专用
     */
    @PostMapping("/api/v2/aiagent/describeAIAgentInstance")
    public Map<String, Object> describeAIAgentInstance(@RequestBody Map<String, Object> request) {
        try {
            String userId = (String) request.get("user_id");
            String instanceId = (String) request.get("ai_agent_instance_id");
            String region = (String) request.get("region");

            log.info("描述伴伴AI实例请求 - 用户ID: {}, 实例ID: {}, 区域: {}", userId, instanceId, region);
            
            // 验证必需参数
            if (userId == null || userId.trim().isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", 400);
                errorResult.put("message", "用户ID不能为空");
                return errorResult;
            }
            if (instanceId == null || instanceId.trim().isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", 400);
                errorResult.put("message", "伴伴AI实例ID不能为空");
                return errorResult;
            }

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            result.put("request_id", UUID.randomUUID().toString());
            result.put("status", "Running");
            result.put("template_config", "{\"voice_id\":\"zhixiaoxia\",\"volume\":50}");
            result.put("runtime_config", "{\"max_idle_time\":300}");
            result.put("user_data", userId);
            result.put("call_log_url", "");

            log.info("伴伴AI实例描述成功 - 实例ID: {}, 状态: Running", instanceId);
            return result;

        } catch (Exception e) {
            log.error("描述伴伴AI实例异常: {}", e.getMessage(), e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "描述伴伴AI实例失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 生成消息聊天Token - 语音通话专用
     */
    @PostMapping("/api/v2/aiagent/generateMessageChatToken")
    public Map<String, Object> generateMessageChatToken(@RequestBody Map<String, Object> request) {
        try {
            String userId = (String) request.get("user_id");
            String aiAgentId = (String) request.get("ai_agent_id");
            String region = (String) request.get("region");

            log.info("生成消息聊天Token请求 - 用户ID: {}, 伴伴AI ID: {}, 区域: {}", userId, aiAgentId, region);
            
            // 验证必需参数
            if (userId == null || userId.trim().isEmpty()) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("code", 400);
                errorResult.put("message", "用户ID不能为空");
                return errorResult;
            }

            // 生成聊天Token信息
            String appId = "894a88b1eafd46eeae79a0b559fb256a";
            String token = "chat_token_" + System.currentTimeMillis();
            String nonce = UUID.randomUUID().toString().substring(0, 8);
            long timestamp = System.currentTimeMillis();
            String appSign = sha256(appId + token + userId + timestamp);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "success");
            result.put("request_id", UUID.randomUUID().toString());
            result.put("app_id", appId);
            result.put("token", token);
            result.put("user_id", userId);
            result.put("nonce", nonce);
            result.put("role", "user");
            result.put("timestamp", timestamp);
            result.put("app_sign", appSign);

            log.info("消息聊天Token生成成功 - 用户ID: {}, Token: {}", userId, token);
            return result;

        } catch (Exception e) {
            log.error("生成消息聊天Token异常: {}", e.getMessage(), e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "生成消息聊天Token失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 获取客户端时间戳（24小时后过期）
     */
    private long getClientTimestamp() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime().getTime() / 1000;
    }

    /**
     * 创建Base64编码的RTC认证Token
     */
    private String createBase64Token(String channelId, String userId, long timestamp) {
        String rtcAuthStr = String.format("%s%s%s%s%d", liveMicAppId, liveMicAppKey, channelId, userId, timestamp);
        String rtcAuth = sha256(rtcAuthStr);
        
        // 手动构建JSON字符串
        String tokenJson = String.format(
            "{\"appid\":\"%s\",\"channelid\":\"%s\",\"userid\":\"%s\",\"nonce\":\"\",\"timestamp\":%d,\"token\":\"%s\"}",
            liveMicAppId, channelId, userId, timestamp, rtcAuth
        );
        
        return Base64.getEncoder().encodeToString(tokenJson.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * SHA256签名
     */
    private static String sha256(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
